#ifndef _BitPacker_h_
#define _BitPacker_h_

#include <fstream>
#include <list>
#include <iostream>
#include <sstream>
#include <time.h>
#include "Command.h"
#include "ViewCommand.h"
#include "MoveCommand.h"

class BitPacker
{
public:
	BitPacker (void) {
		// Create unique name
		time_t seconds;
		seconds = time(NULL);

		// Int to string
		stringstream ss;
		ss << seconds << ".rep";
		mFileNameS = ss.str();
		mFileName = (char*) ss.str().c_str();
		
		mOfstream.open("replay.bin");
		//mOfstream.open(mFileName);
	}
	
	BitPacker (string name) {
		mFileNameS = name;
		mFileName = (char *) name.c_str();
		mIfstream.open(mFileName);
	}
	
	virtual ~BitPacker (void) {
		// close streams
		if (mIfstream.is_open()) {
			mIfstream.close();
		} else if (mOfstream.is_open()) {
			mOfstream.close();
		}
	}
	
	void getCommands(list<Command*> *commands) {
		int i;
		int type;
		mIfstream.read((char*) &i, sizeof(int));
		for (int x = 0 ; x < i ; x++) {
			mIfstream.read((char*) &type, sizeof(int));
			Command *tmp;
			if (type == 1) {
				tmp = new MoveCommand();
				tmp->load(mIfstream);
			} else if (type == 2) {
				tmp = new ViewCommand();
				tmp->load(mIfstream);
			}
			commands->push_back(tmp);
		}
	}
	
	void addCommands(list<Command*> &commands) {
		list<Command*>::iterator it;
		
		// Declaring the size of this commandlist
		int i = commands.size();
		mOfstream.write((char*) &i, sizeof(int));
		
		for (it = commands.begin() ; it != commands.end() ; it++) {
			(*it)->save(mOfstream);
		}
	}
	
	string getFileName() {
		return mFileNameS;
	}

private:
	ofstream mOfstream;
	char *mFileName;
	string mFileNameS;
	ifstream mIfstream;
};

#endif
